package com.wj.springboot2demo.mq;

import java.util.Map;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnCallback;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/***
 * 生产者
 */
@Component
public class RabbitMqProducer extends BabbitMqTest{

    @Autowired
    private RabbitTemplate rabbitTemplate;
    
    final ReturnCallback returnCallback = new ReturnCallback() {
        
        @Override
        public void returnedMessage(org.springframework.amqp.core.Message message, int replyCode, String replyText, 
                String exchange, String routingKey) {
        	log("producer ReturnCallback : returnedMessage");
        }
    };
    
    final ConfirmCallback confirmCallback = new ConfirmCallback() {
        
    	//手动确认消息
        @Override
        public void confirm(CorrelationData correlationData, boolean ack, String cause) {
            log("producer ConfirmCallback : " + correlationData + ", " + ack + ", " + cause);
        }
    };
    
    /**
     * 
     * @param messageObject payload
     * @param properties 消息map
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public void send(Object messageObject, Map<String, Object> properties) {
    	System.out.println("===========================");
        MessageHeaders messageHeaders = new MessageHeaders(properties);
        
        //消费者接收的内容就是这个
        //这里只是按标准定义了一个消息内容，其实这里只要是序列化的对象，都可以
        Message<Object> message = MessageBuilder.createMessage(messageObject, messageHeaders);
        
        //消费者ack之后执行
        rabbitTemplate.setConfirmCallback(confirmCallback);
        
        rabbitTemplate.setReturnCallback(returnCallback);
        
        CorrelationData data = new CorrelationData("wjyuian123456");

        log("producer send message");
        //往交换器发消息
        rabbitTemplate.convertAndSend("rabbitmq-1", "springboot2.queue", message, data);
    }
}
